﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestLogRealtimeMonitor.Helpers;

namespace TestLogRealtimeMonitor.Infrastructures
{
    public class FileListenerServer
    {

        private Action<string> ResolveFileDelegate;
        private  FileSystemWatcher watcher;
        public FileListenerServer()
        {
                
        }
        public FileListenerServer(string path,Action<string> ResolveFileCallBack)
        {
            try
            {
                watcher=new FileSystemWatcher();
                watcher.Path = path;
                watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.DirectoryName;
                watcher.IncludeSubdirectories = true;
                watcher.Created += new FileSystemEventHandler(FileWatcher_Created);
                watcher.Changed += new FileSystemEventHandler(FileWatcher_Changed);
                ResolveFileDelegate = ResolveFileCallBack;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
                throw new Exception(ex.Message);
            }
        }

        private void FileWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            //ResolveFileDelegate?.Invoke(e.FullPath);
        }

        private void FileWatcher_Created(object sender, FileSystemEventArgs e)
        {
            ResolveFileDelegate?.Invoke(e.FullPath);
        }
        public void Start()
        { 
          watcher.EnableRaisingEvents = true;
        }
        public void Stop()
        {
            watcher.EnableRaisingEvents = false;
            watcher.Dispose();
            watcher = null;
        }
       
    }
}
